#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_err.h"
#include "esp_timer.h"

#include "wifi_station_softap.h"
#include "server_spiffs.h"
#include "ap_http_server.h"
#include "ap_dns_pase.h"
#include "button.h"

#include "lvgl_gui_lib.h"

static void lv_tick_task(void *arg)
{
    /* 通知LVGL已经过了多少毫秒 */
    lv_tick_inc(1);
}

void app_main() 
{
    config_esp_module val = ESP_DNS;

    // disable_tft_lcd_blk();

    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    // 初始化按键
    button_init();

    // 设置spiffs文件系统
    esp_spiffs_module();

    // WIFI STA是否未初始配置
    val = get_config_module();
    if (val == AP_DNS) {
        // 未配置 AP DNS模式
        ap_dns_pase_start();
    } else if (val == AP_STA) {
        // 配置AP STA模式
        esp_wifi_station_main();
    }

    ap_http_demo();


#if CONFIG_LVGL_LIB_INIT

    lvgl_gui_init();
    /* 为 LVGL 提供时基单元 */
    const esp_timer_create_args_t periodic_timer_args = {
        .callback = &lv_tick_task,
        .name = "periodic_gui"};
    esp_timer_handle_t periodic_timer = NULL;
    ESP_ERROR_CHECK(esp_timer_create(&periodic_timer_args, &periodic_timer));
    ESP_ERROR_CHECK(esp_timer_start_periodic(periodic_timer, 1 * 1000));

#endif

#if CONFIG_LVGL_GUI_GUIDER
    setup_ui(&guider_ui);       //设计小部件的ui布局
    events_init(&guider_ui);    //设置小部件的事件
    // custom_init(&guider_ui);    //运行自定义的程序
#endif

    while (1) {
        #if CONFIG_LVGL_LIB_INIT
            lv_task_handler(); /* LVGL 计时器 */
        #endif
        /* Delay 1 tick (set freq 1000HZ assumes FreeRTOS tick is 1ms */
        vTaskDelay(pdMS_TO_TICKS(10));
    }
}